package com.aiwei.tdjk.service.impl;

import com.aiwei.tdjk.bean.Pager;
import com.aiwei.tdjk.dao.extend.AuthExtendMapper;
import com.aiwei.tdjk.dto.request.GetAuthPagerRequest;
import com.aiwei.tdjk.entity.Auth;
import com.aiwei.tdjk.entity.AuthExample;
import com.aiwei.tdjk.entity.Group;
import com.aiwei.tdjk.entity.User;
import com.aiwei.tdjk.service.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * Created by yanfeng on 2016/12/13.
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthExtendMapper authExtendMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private GroupService groupService;
    @Autowired
    private SysGroupRelationService sysGroupRelationService;
    @Autowired
    private GroupRelationService groupRelationService;


    @Override
    public Auth get(Long id) {
        return authExtendMapper.selectByPrimaryKey(id);
    }

    @Override
    public void update(Auth auth) {
        authExtendMapper.updateByPrimaryKeySelective(auth);
    }

    @Override
    public Set<Long> findRoleIds(Long userId, Set<Long> groupIds, Set<Long> organizationIds, Set<Long> jobIds, Set<Long[]> organizationJobIds) {

        HashMap<String,Object> map = new HashMap<>();
        map.put("userId",userId);
        map.put("groupIds",groupIds);
        map.put("organizationIds",organizationIds);
        map.put("jobIds",jobIds);
        return authExtendMapper.findRoleIds(map);

    }

    @Override
    public Pager<Auth> find(GetAuthPagerRequest request) {
        request.webParamConvert();
        List<Auth> groupList = authExtendMapper.find(request);
        int totalCount = authExtendMapper.getTotalCount(request);
        Pager<Auth> pager = new Pager<>();
        pager.setPageNumber(request.getPageNumber());
        pager.setPageSize(request.getPageSize());
        pager.setList(groupList);
        pager.setTotalCount(totalCount);
        return pager;
    }

    @Override
    public void addUserAuth(Long[] userIds, Auth m) {


        if (ArrayUtils.isEmpty(userIds)) {
            return;
        }

        for (Long userId : userIds) {

            User user = userService.get(userId);
            if (user == null) {
                continue;
            }

            Auth auth = findByUserId(userId);
            if (auth != null) {
                //todo 是否编辑这里呢？
                //.addRoleIds(m.getRoleIds());
                continue;
            }
            auth = new Auth();
            auth.setUserId(userId);
            auth.setType(m.getType());
            auth.setRoleIds(m.getRoleIds());

            authExtendMapper.insertSelective(auth);
        }

    }

    private Auth findByUserId(Long userId) {
        AuthExample example = new AuthExample();
        example.or().andUserIdEqualTo(userId);
        List<Auth> auths = authExtendMapper.selectByExample(example);
        if (auths.isEmpty())
            return null;
        return  authExtendMapper.selectByExample(example).get(0);
    }

    @Override
    public int delete(Long id) {
        return authExtendMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int delete(Long[] ids) {
        if (ids!=null&&ids.length>0){
            for (Long id:ids){
                delete(id);
            }
            return ids.length;
        }
        return 0;
    }

    @Override
    public void addGroupAuth(Long[] groupIds, Auth m) {
        if (ArrayUtils.isEmpty(groupIds)) {
            return;
        }

        for (Long groupId : groupIds) {
            Group group = groupService.get(groupId);
            if (group == null) {
                continue;
            }

            Auth auth = findByGroupId(groupId);
            if (auth != null) {
                //todo 是否编辑这里呢？
                //auth.addRoleIds(m.getRoleIds());
                continue;
            }
            auth = new Auth();
            auth.setGroupId(groupId);
            auth.setType(m.getType());
            auth.setRoleIds(m.getRoleIds());
            authExtendMapper.insertSelective(auth);
        }
    }


    @Override
    public void addOrganizationJobAuth(Long[] organizationIds, Long[][] jobIds, Auth m) {

        if (ArrayUtils.isEmpty(organizationIds)) {
            return;
        }
        for (int i = 0, l = organizationIds.length; i < l; i++) {
            Long organizationId = organizationIds[i];
            if (jobIds[i].length == 0) {
                addOrganizationJobAuth(organizationId, null, m);
                continue;
            }

            //仅新增/修改一个 spring会自动split（“，”）--->给数组
            if (l == 1) {
                for (int j = 0, l2 = jobIds.length; j < l2; j++) {
                    Long jobId = jobIds[i][0];
                    addOrganizationJobAuth(organizationId, jobId, m);
                }
            } else {
                for (int j = 0, l2 = jobIds[i].length; j < l2; j++) {
                    Long jobId = jobIds[i][0];
                    addOrganizationJobAuth(organizationId, jobId, m);
                }
            }

        }
    }

    /**
     * 根据角色查找用户ids
     * 1、先根据角色查找组，然后再根据组查找用户id
     * 2、根据角色直接查找用户id
     * 3、把上面两步查找的用户id放在set集合中去
     *
     * @param roleIds
     */
    @Override
    public Set<Long> findUserIdsByRoleIds(List<String> roleIds) {
        Set<Long> userIds = Sets.newHashSet();
        AuthExample authExample = new AuthExample();
        authExample.or().andRoleIdsIn(roleIds);
        List<Auth> authList  = authExtendMapper.selectByExample(authExample);
        for (Auth auth:authList) {
            if(auth.getType().equals("user_group")){//如果是用户组，则调用根据组查用户的方法
                List<Long> userIdList = sysGroupRelationService.findUserIdsByGroupId(auth.getGroupId());
                if(userIdList!=null&&userIdList.size()>0){
                    userIds.addAll(userIdList);
                }
            }else{//如果是用户的话，直接把userId放到集合中去
                userIds.add(auth.getUserId());
            }
        }
        return userIds;
    }

    @Override
    public List<Long> getUsersOfRoleByRoleIds(List<Long> laneUserIds,List<String> roleIds) {
        List<Long> newList = Lists.newArrayList();
        Set<Long> doctorUserIds = findUserIdsByRoleIds(roleIds);//根据角色查找用户ids
        for(Long laneUserId:laneUserIds){
            for(Long doctorUserId:doctorUserIds){
                if(laneUserId.longValue() == doctorUserId.longValue()){     //会员对应坊中匹配到该角色的用户
                    newList.add(laneUserId);
                }
            }
        }
        return newList;
    }

    /**
     * 根據角色查用戶組
     *
     * @param roleIds
     */
    @Override
    public List<Long> findGroupIdsByRoleIds(List<String> roleIds) {
        List<Long> groupIds = Lists.newArrayList();
        AuthExample authExample = new AuthExample();
        authExample.or().andRoleIdsIn(roleIds).andTypeEqualTo("user_group");
        List<Auth> authList  = authExtendMapper.selectByExample(authExample);
        for (Auth auth:authList) {
            groupIds.add(auth.getGroupId());
        }
        return groupIds;
    }

    /**
     * 根据登陆用户id获取其角色
     *
     * @param userId
     */
    @Override
    public String getRoleByUserId(Long userId) {
        String roleId ="";
        AuthExample authExample = new AuthExample();
        authExample.or().andUserIdEqualTo(userId);
        List<Auth> authList  = authExtendMapper.selectByExample(authExample);
        if(authList!=null && authList.size()>0){
            for (Auth auth:authList) {
                roleId = auth.getRoleIds();
            }
        }else{
            List<Long> groupIds = sysGroupRelationService.findGroupIdsByUserId(userId);
            if(groupIds.size()==1){
                AuthExample authExample1 = new AuthExample();
                authExample1.or().andGroupIdEqualTo(groupIds.get(0));
                List<Auth> authList1  = authExtendMapper.selectByExample(authExample1);
                if(authList1!=null && authList1.size()>0){
                    roleId = authList1.get(0).getRoleIds();
                }
            }
        }
        return roleId;
    }

    private void addOrganizationJobAuth(Long organizationId, Long jobId, Auth m) {
        if (organizationId == null) {
            organizationId = 0L;
        }
        if (jobId == null) {
            jobId = 0L;
        }


        Auth auth = findByOrganizationIdAndJobId(organizationId, jobId);

        if (auth != null) {
            //auth.addRoleIds(m.getRoleIds());
            return;
        }
        auth = new Auth();
        auth.setOrganizationId(organizationId);
        auth.setJobId(jobId);
        auth.setType(m.getType());
        auth.setRoleIds(m.getRoleIds());
        authExtendMapper.insertSelective(auth);

    }

    private Auth findByOrganizationIdAndJobId(Long organizationId, Long jobId) {
        AuthExample example = new AuthExample();
        example.or().andOrganizationIdEqualTo(organizationId).andJobIdEqualTo(jobId);
        List<Auth> auths = authExtendMapper.selectByExample(example);
        if (auths.isEmpty())
            return null;
        return  authExtendMapper.selectByExample(example).get(0);
    }


    private Auth findByGroupId(Long groupId) {
        AuthExample example = new AuthExample();
        example.or().andGroupIdEqualTo(groupId);
        List<Auth> auths = authExtendMapper.selectByExample(example);
        if (auths.isEmpty())
            return null;
        return  authExtendMapper.selectByExample(example).get(0);
    }
}
